package com.example.demo.practice.ui;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * 报警红色文字
 * 故障黄色文字
 * 正常绿色文字
 */

public class AlarmTextView extends TextView{

    private String mText;
    private Paint mPaint;
    private Rect mBound;
    public AlarmTextView(Context context) {
        super(context);
    }

    public AlarmTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mText= (String) getText();
        init();
    }

    private void init() {

        int mTextColor = Color.GREEN;
        int mTextSize = 40;

        switch (mText){
            case "报警":mTextColor=Color.RED;
                break;
            case "故障":mTextColor=Color.YELLOW;
                break;
            default:break;
        }
        mPaint = new Paint();
        mPaint.setTextSize(mTextSize);
        mPaint.setColor(mTextColor);
        //获得绘制文本的宽和高
        mBound = new Rect();
        mPaint.getTextBounds(mText, 0, mText.length(), mBound);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        mText= (String) text;
        init();
        this.invalidate();
        super.setText(text, type);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //绘制文字
        canvas.drawText(mText, getWidth() / 2 - mBound.width() / 2, getHeight() / 2 + mBound.height() / 2, mPaint);
    }
}
